<script lang="jsx" setup>
import { nextTick, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import { PlusOutlined } from '@ant-design/icons-vue';
import { DatePicker, Input, InputNumber } from 'ant-design-vue';
import dayjs from 'dayjs';
import { isNumber } from 'lodash-es';
import { getAddFeedModelData } from '@/service/api/modules/work-order-management/production-feed';
import EngineeringInstruction from './engineering-instruction.vue';
import Drawing from './drawing.vue';
import AddSheetMetal from './add-sheet-metal.vue';

const props = defineProps({
  rowData: {
    type: Object,
    required: true
  }
});

console.log('props', props.rowData);

const rowData = props.rowData;
const topTableRef = ref(null);

const topSearchParams = ref({
  prodId: rowData.prodID,
  tlqty: null
});

const engineeringInstructionRef = ref(null);

const formRef = ref(null);
const topModel = ref({
  liaohao: null,
  prodOrderNo: null,
  pedifficulty: null,
  mantissaPercent: null,
  invProvideQty: null,
  invQty: null,
  qty: null,
  invQty: null,
  issueType: '投料',
  issPcsQty: null,
  scrapRete: null,
  sheetQty: null,
  autoCalc: [true],
  workType: '正常',
  lotQty: 120,
  list: null,
  remark: null
});

function resetTopModel() {
  topModel.value = {
    liaohao: null,
    prodOrderNo: null,
    pedifficulty: null,
    mantissaPercent: null,
    invProvideQty: null,
    invQty: null,
    qty: null,
    invQty: null,
    issueType: '投料',
    issPcsQty: null,
    scrapRete: null,
    sheetQty: null,
    autoCalc: [true],
    workType: '正常',
    lotQty: 120,
    list: null,
    remark: null
  };
}

function getComputeData() {
  getAddFeedModelData({
    prodId: rowData.prodID,
    issPlanId: rowData.issPlanID,
    tlqty: topModel.value.issPcsQty
  }).then(({ data, error }) => {
    if (!error) {
      topModel.value.scrapRete = data.bestUtilization;
      topModel.value.sheetQty = data.worstUtilization;
    }
  });
  topSearchParams.value.tlqty = topModel.value.issPcsQty;
  nextTick(() => {
    topTableRef.value.getData();
  });
}

const topTableData = ref([]);
function handleTopTableDataLoadSuccess(data) {
  topTableData.value = data;
}

nextTick(() => {
  // 获取工程指示tab
  engineeringInstructionRef.value.getData({
    prodId: rowData.prodID,
    techId: rowData.techid
  });
});

if (props.rowData) {
  topModel.value = rowData;
  // topModel.value.editQty =
  //   topModel.value.qty - topModel.value.issPcsQty - topModel.value.prodOdrInvQty < 0
  //     ? 0
  //     : topModel.value.qty - topModel.value.issPcsQty - topModel.value.prodOdrInvQty;
  topModel.value.editQty = topModel.value.qty;
  topModel.value.invProvideQty = topModel.value.invProvideQty || 0;
  topModel.value.issueType = topModel.value.issueType || '投料';
  topModel.value.workType = topModel.value.workType || '正常';
  topModel.value.autoCalc = [true];
  topModel.value.issPcsQty = topModel.value.editQty - topModel.value.invProvideQty;
  topModel.value.lotQty = topModel.value.lotQty || 120;
  getComputeData();
}

const formList = [
  {
    type: 'input',
    key: 'liaohao',
    label: '生产型号',
    span: 12,
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    key: 'prodOrderNo',
    label: '工单号',
    span: 12,
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    key: 'pedifficulty',
    label: '难度系数',
    span: 12,
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    key: 'mantissaPercent',
    label: '尾数板比率',
    span: 12,
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    key: 'invProvideQty',
    label: '使用库存数',
    span: 6,
    placeholder: '请输入使用库存数',
    keypressEnter: () => {
      const computeVal = topModel.value.issPcsQty - topModel.value.invProvideQty;
      if (computeVal < 0) {
        window.$message.error('投料数(PCS)必须大于0');
      }
      topModel.value.issPcsQty = computeVal;
      if (topModel.value.autoCalc.includes(true)) {
        getComputeData();
      }
    },
    blur() {
      const computeVal = topModel.value.issPcsQty - topModel.value.invProvideQty;
      if (computeVal < 0) {
        window.$message.error('投料数(PCS)必须大于0');
      }
      topModel.value.issPcsQty = computeVal;
      if (topModel.value.autoCalc.includes(true)) {
        getComputeData();
      }
    },
    rule: [
      {
        required: true,
        message: '请输入使用库存数',
        trigger: 'change'
      }
    ]
  },
  {
    type: 'input',
    key: 'invQty',
    label: '库存数量',
    span: 6,
    placeholder: '',
    disabled: true
  },
  {
    type: 'input',
    key: 'editQty',
    label: '待投数量',
    span: 6,
    placeholder: '请输入待投数量'
  },
  {
    type: 'input',
    key: 'qty',
    label: '订单数量',
    span: 6,
    placeholder: '',
    disabled: true
  },
  {
    type: 'select',
    key: 'issueType',
    label: '投料类型',
    span: 12,
    placeholder: '请选择投料类型',
    selectOptions: [
      {
        label: '投料',
        value: '投料'
      },
      {
        label: '补料',
        value: '补料'
      }
    ]
  },
  {
    type: 'input',
    key: 'issPcsQty',
    label: '投料数(PCS)',
    span: 12,
    placeholder: '请输入投料数(PCS)',
    keypressEnter: () => {
      const computeVal = topModel.value.issPcsQty - topModel.value.invProvideQty;
      if (computeVal < 0) {
        window.$message.error('投料数(PCS)必须大于0');
      }
      topModel.value.issPcsQty = computeVal;
      if (topModel.value.autoCalc.includes(true)) {
        getComputeData();
      }
    },
    blur() {
      const computeVal = topModel.value.issPcsQty - topModel.value.invProvideQty;
      if (computeVal < 0) {
        window.$message.error('投料数(PCS)必须大于0');
      }
      topModel.value.issPcsQty = computeVal;
      if (topModel.value.autoCalc.includes(true)) {
        getComputeData();
      }
    },

    rule: [
      {
        required: true,
        message: '请输入投料数(PCS)',
        trigger: 'change'
      }
    ]
  },

  {
    type: 'input',
    key: 'scrapRete',
    label: '预投料率(%)',
    span: 12,
    placeholder: '请输入预投料率(%)'
  },
  {
    type: 'input',
    key: 'sheetQty',
    label: '大料数',
    span: 6,
    placeholder: '请输入大料数'
  },
  {
    type: 'checkbox',
    key: 'autoCalc',
    label: '',
    span: 6,
    selectOptions: [
      {
        label: '自动计算',
        value: true
      }
    ]
  },
  {
    type: 'select',
    key: 'workType',
    label: '工单类型',
    span: 12,
    placeholder: '请选择工单类型',
    selectOptions: [
      {
        label: '正常',
        value: '正常'
      },
      {
        label: '赶板',
        value: '赶板'
      },
      {
        label: '加急',
        value: '加急'
      }
    ]
  },
  {
    type: 'input',
    key: 'lotQty',
    label: '每批卡数量',
    span: 12,
    placeholder: '请输入每批卡数量'
  },
  // {
  //   type: 'input',
  //   key: 'list',
  //   label: '历史报废率',
  //   span: 6,
  //   placeholder: '',
  //   disabled: true
  // },
  {
    type: 'textarea',
    key: 'remark',
    label: '备注',
    span: 24,
    placeholder: ''
  }
];

const topFormRef = ref(null);

const { height } = useElementSize(topFormRef);

const topColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'liaohao',
    dataIndex: 'liaohao',
    title: '生产型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return <div class="fonw-800 color-#646cff">{record.liaohao}</div>;
    }
  },
  {
    key: 'sheetpnl',
    dataIndex: 'sheetpnl',
    title: '1Sheet=?PNL',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'pnlset',
    dataIndex: 'pnlset',
    title: '1PNL=?Set',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'setpcs',
    dataIndex: 'setpcs',
    title: '1Set=?Pcs',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'pnl',
    dataIndex: 'pnl',
    title: 'PNL数',
    align: 'center',
    checked: true,
    ellipsis: true
  }
];
const isPositiveNumber = str => {
  // 使用正则表达式匹配大于0的数字
  return /^(\d+(\.\d+)?)$/.test(str) && Number.parseFloat(str) > 0;
};

const bottomTableRef = ref(null);
const bottomSearchParams = ref({});
const bottomColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'prodNo',
    dataIndex: 'prodNo',
    title: '生产型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150,
    customRender: ({ record }) => {
      return <div class="fonw-800 color-#646cff">{record.prodNo}</div>;
    }
  },
  {
    key: 'matno',
    dataIndex: 'matno',
    title: '板材编码',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },
  {
    key: 'specif',
    dataIndex: 'specif',
    title: '物料规格',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200
  },
  {
    key: 'invqty',
    dataIndex: 'invqty',
    title: '库存数量',
    align: 'center',
    checked: true,
    ellipsis: true,

    width: 150
  },
  {
    key: 'applyQty',
    dataIndex: 'applyQty',
    title: '申请数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.applyQty}
          onChange={e => {
            const reg = /^\d+$/;
            if (!reg.test(e.target.value)) {
              window.$message.error('请输入正整数');
              record.applyQty = 0;
              e.target.value = 0;
              return;
            }
            if (e > Number(record.invqty)) {
              window.$message.error('申请数量不能大于库存数量');
              record.applyQty = 0;
              e.target.value = 0;
              return;
            }
            e.target.value = Number(e.target.value);
            record.applyQty = Number(e.target.value);
            console.log('record', record);
          }}
        ></Input>
      );
    }
  },
  {
    key: 'unit',
    dataIndex: 'unit',
    title: '单位',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'length',
    dataIndex: 'length',
    title: '实开大料长(mm)',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.length}
          onChange={e => {
            if (!isPositiveNumber(e.target.value)) {
              window.$message.error('请输入大于0的数字');
              e.target.value = record.length;
              return;
            }
            record.length = Number(e.target.value);
          }}
        ></Input>
      );
    }
  },
  {
    key: 'width',
    dataIndex: 'width',
    title: '实开大料宽(mm)',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.width}
          onChange={e => {
            if (!isPositiveNumber(e.target.value)) {
              window.$message.error('请输入大于0的数字');
              record.width = 0;
              return;
            }
            record.width = Number(e.target.value);
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.remark}
          onChange={e => {
            record.remark = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'asheetPnl',
    dataIndex: 'asheetPnl',
    title: 'APNL/Sheet',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.asheetPnl}
          onChange={e => {
            if (!isPositiveNumber(e.target.value)) {
              window.$message.error('请输入大于0的数字');
              record.asheetPnl = 0;
              e.target.value = record.asheetPnl;
              return;
            }
            record.asheetPnl = Number(e.target.value);
          }}
        ></Input>
      );
    }
  },
  {
    key: 'APnlQty',
    dataIndex: 'APnlQty',
    title: '开APNL',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      if (topModel.value.autoCalc.includes(true)) {
        return record.applyQty * (record.asheetPnl || 0);
      }
      return null;
    }
  },
  {
    key: 'bsheetPnl',
    dataIndex: 'bsheetPnl',
    title: 'BPNL/Sheet',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return (
        <Input
          class="w-full"
          v-model:value={record.bsheetPnl}
          onChange={e => {
            if (!isPositiveNumber(e.target.value)) {
              window.$message.error('请输入大于0的数字');
              record.bsheetPnl = 0;
              return;
            }
            e.target.value = Number(e.target.value);
            record.bsheetPnl = Number(e.target.value);
          }}
        ></Input>
      );
    }
  },
  {
    key: 'BPnlQty',
    dataIndex: 'BPnlQty',
    title: '开BPNL',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      if (topModel.value.autoCalc.includes(true)) {
        return record.applyQty * (record.bsheetPnl || 0);
      }
    }
  },
  {
    key: 'needDate',
    dataIndex: 'needDate',
    title: '需求日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200,
    customRender: ({ record }) => {
      return (
        <DatePicker
          value={record.needDate}
          format="YYYY-MM-DD HH:mm:ss"
          onChange={e => (record.needDate = e)}
        ></DatePicker>
      );
    }
  },
  {
    key: 'proviQty',
    dataIndex: 'proviQty',
    title: '发放数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160
  }
];

const activeKey = ref('1');

const visible = ref(false);
const sheetMetalList = ref([]);
const engineeringTableData = ref([]);
function handleEngineeringTableDataLoadSuccess(data) {
  console.log('`````````````````````', data);
  engineeringTableData.value = data;
}

const engineeringInstructionData = ref([]);
function handleEngineeringInstructionTableLoadSuccess(data) {
  console.log('engineeringInstructionData', data);
  engineeringInstructionData.value = data;
}

function handleAdd() {
  visible.value = true;
}

const addSheetMetalRef = ref(null);
function handleSaveSheetMetal() {
  const data = addSheetMetalRef.value.saveData();
  let asheetPnl = null;
  let bsheetPnl = null;
  if (topModel.value?.liaohao?.includes('-')) {
    // 为AB板
    asheetPnl =
      topTableData.value.find(item => {
        if (item?.liaohao.split('-')[1] === 'A') {
          return item;
        }
      })?.sheetpnl || null;
    bsheetPnl =
      topTableData.value.find(item => {
        if (item?.liaohao.split('-')[1] === 'B') {
          return item;
        }
      })?.sheetpnl || null;
  } else {
    asheetPnl = topTableData.value[0].sheetpnl;
  }
  if (data) {
    const prodNo = topModel.value.liaohao.split('-')[0];
    sheetMetalList.value = [
      ...sheetMetalList.value,
      {
        ...data,
        prodNo,
        applyQty: 0,
        needDate: dayjs(),
        asheetPnl,
        bsheetPnl,
        dataIndex: sheetMetalList.value.length + 1
      }
    ];
    visible.value = false;
  }

  console.log('sheetMetalList.value', sheetMetalList.value);
}

function handleDel(data) {
  const index = data.index;
  sheetMetalList.value.splice(index, 1);
  sheetMetalList.value.forEach((item, idx) => {
    item.dataIndex = idx + 1;
  });
  sheetMetalList.value = [...sheetMetalList.value]; // 不这么写不触发更新视图
  data.hidePopup();
}

function handleSaveData(data) {
  // 判断生产型号是否为AB板
  console.log('保存了');

  if (data) {
    sheetMetalList.value = [
      ...sheetMetalList.value,
      {
        ...data,
        prodNo,
        applyQty: 0,
        needDate: dayjs(),
        asheetPnl,
        bsheetPnl
      }
    ];
    visible.value = false;
  }
}

function saveData() {
  const model = topModel.value;
  console.log('model', model);

  const data = {
    moduleNo: model.liaohao,
    remark: model.remark,
    issueType: model.issueType,
    autoCalc: model.autoCalc[0],
    workType: model.workType,
    scrapRete: model.scrapRete,
    issPcsQty: model.issPcsQty,
    custProdNo: model.custProdNo,
    sheetQty: model.sheetQty,
    // prodOrderId: model.prodOrderNo,
    liveUint: model.liveUint || 0,
    prodId: model.prodID,
    qty: model.qty,
    lotQty: model.lotQty,
    pedifficulty: model.pedifficulty,
    prodOrderNo: model.prodOrderNo
  };

  let index = -1;
  const list = sheetMetalList.value.map(item => {
    if (item.applyQty === 0) {
      index = item.dataIndex;
    }
    return {
      moduleNo: model.liaohao,
      type: item.type,
      matId: item.matid,
      matName: item.matname,
      // barcode:item.
      qty: item.applyQty,
      // prodDate:item.
      prodOrderNo: model.prodOrderNo,
      unit: item.unit,
      specif: item.specif,
      outType: model.issueType
    };
  });

  if (!list.length) {
    window.$message.error('请选择板材');
    return false;
  }

  if (index > -1) {
    window.$message.error(`请先填写第${index}行板材申请数量`);
    return false;
  }

  return { data, list };
}

defineExpose({
  saveData,
  resetTopModel
});
</script>

<template>
  <div class="add-modal-content h-full w-full">
    <ARow :gutter="16" class="h-full w-full">
      <ACol :span="14" class="h-full">
        <ACard ref="topFormRef" :bordered="false" class="modal-card" :body-style="{ padding: '5px' }">
          <template #title>
            <span class="mr15px color-#646cff">投产输入</span>
          </template>
          <Form ref="formRef" v-model:model="topModel" class="add-modal" :form-list="formList"></Form>
        </ACard>
        <div class="bottom-table w-full" :style="{ height: `calc(100% - ${height}px)` }">
          <Table
            ref="topTableRef"
            v-model:searchParams="topSearchParams"
            :column="topColumn"
            :show-row-selection="false"
            auto-generate-uuid
            row-key="screenId"
            :scroll="{ y: 'auto' }"
            is-init-get-data
            url="/mes/BaseVppcissueplanodr/getModelList1"
            class="h-50%"
            :is-pagination="false"
            @table-data-load-sucess="handleTopTableDataLoadSuccess"
          >
            <template #title>
              <span class="color-#646cff">投料型号</span>
            </template>
          </Table>
          <Table
            ref="bottomTableRef"
            v-model:searchParams="bottomSearchParams"
            :column="bottomColumn"
            :show-row-selection="false"
            auto-generate-uuid
            :data-source="sheetMetalList"
            row-key="screenId"
            :scroll="{ y: 'auto' }"
            is-init-get-data
            url=""
            class="h-50%"
            :is-pagination="false"
          >
            <template #title>
              <span class="color-#646cff">投发板料</span>
              <AButton type="primary" class="mini-btn ml-8px mr-8px" size="small" ghost @click="handleAdd">
                <template #icon>
                  <PlusOutlined class="align-sub" />
                </template>
                添加
              </AButton>
            </template>
            <template #contextmenuPopup-orter="{ args }">
              <li class="popup-item" @click="handleDel(args)">
                <SvgIcon local-icon="delete" class="text-16px"></SvgIcon>
                删除
              </li>
            </template>
          </Table>
        </div>
      </ACol>
      <ACol :span="10" class="h-full">
        <ATabs v-model:activeKey="activeKey" type="card" class="my-tabs h-full">
          <ATabPane key="1" force-render>
            <template #tab>
              <span>
                <span class="iconfont icon-gongchengzhishi"></span>
                工程指示
              </span>
            </template>
            <EngineeringInstruction
              ref="engineeringInstructionRef"
              @engineering-table-data-load-success="handleEngineeringTableDataLoadSuccess"
              @engineering-instruction-table-load-success="handleEngineeringInstructionTableLoadSuccess"
            />
          </ATabPane>
          <ATabPane key="2" force-render>
            <template #tab>
              <span>
                <span class="iconfont icon-gongchengtuzhi"></span>
                开料图
              </span>
            </template>
            <Drawing />
          </ATabPane>
        </ATabs>
      </ACol>

      <Modal
        v-model:visible="visible"
        :destroy-on-close="true"
        :centered="true"
        width="90vw"
        height="85vh"
        mask
        :modal-warp-style="{ padding: '5px' }"
      >
        <template #title>
          <div class="add-sheet-metal-title pl-15px">
            请选择要投放的板材 型号：
            <span class="mr-8px color-#646cff">{{ topModel.liaohao }}</span>
            还可领数量：
            <span class="color-#646cff">{{ topModel.sheetQty }}</span>
          </div>
        </template>

        <AddSheetMetal
          ref="addSheetMetalRef"
          :row-data="rowData"
          :engineering-table-data="engineeringTableData"
          :engineering-instruction-data="engineeringInstructionData"
          @save-data="handleSaveData"
        />
        <template #footer>
          <div class="modal-footer">
            <AButton @click="visible = false">关闭</AButton>
            <AButton type="primary" @click="handleSaveSheetMetal">确定</AButton>
          </div>
        </template>
      </Modal>
    </ARow>
  </div>
</template>

<style lang="scss" scoped>
.add-modal-content {
  :deep(.ant-card) {
    &.modal-card {
      .ant-card-head {
        min-height: 30px;
      }
    }
  }
  :deep(.ant-form-item) {
    margin-bottom: 0 !important;
  }
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      margin-bottom: 0;
    }

    .ant-tabs-content-holder {
      height: calc(100% - 40px);
      .ant-tabs-content {
        height: 100%;
        .ant-tabs-tabpane {
          height: 100%;
        }
      }
    }
    .ant-tabs-nav-list {
      .ant-tabs-tab {
        border-radius: 6px 6px 0 0;
      }
      .ant-tabs-tab-active {
        background: #646cff;
        .ant-tabs-tab-btn {
          color: #fff;
        }
      }
    }
  }
}
</style>
